package net.bwie.realtime.jtp.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;

/**
 * 简介说明:
 *
 * @author: LiLi
 * @date: 2025/06/02 20:15:39
 * @version: 1.0
 */
public class CdcDataEtlMapFunction extends RichMapFunction<String, String> {

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
    }

    @Override
    public String map(String value) throws Exception {

        JSONObject jsonObject = JSON.parseObject(value);

        String afterValue = jsonObject.getString("after");
        String beforeValue = jsonObject.getString("before");

        String opValue = jsonObject.getString("op");
        Long tsValue = jsonObject.getLong("ts_ms");

        JSONObject object = jsonObject.getJSONObject("source");

        String dbValue = object.getString("db");
        String tableValue = object.getString("table");

        String operatorValue;

        switch (opValue) {
            case "u":
                operatorValue = "update";
                break;
            case "r":
            case "c":
                operatorValue = "insert";
                break;
            case "d":
                operatorValue = "delete";
                break;
            default:
                operatorValue = "unknown";
        }
        JSONObject newObject = new JSONObject();

        newObject.put("db_name", dbValue);
        newObject.put("table_name", tableValue);
        newObject.put("operate_type", operatorValue);
        newObject.put("ts_ms", tsValue);

        if ("d".equals(opValue)) {
            newObject.put("operate_data", JSON.parseObject(beforeValue));
        } else {
            newObject.put("operate_data", JSON.parseObject(afterValue));
        }

        return newObject.toJSONString();
    }

    @Override
    public void close() throws Exception {
        super.close();
    }
}
